package com.jfree.nettyshow.config;

import com.jfree.nettyshow.common.HandlerManager;
import com.jfree.nettyshow.common.SessionManager;
import com.jfree.nettyshow.common.SpringUtil;
import com.jfree.nettyshow.entity.Session;
import com.jfree.nettyshow.inter.TaskHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class NettyConfiguration {

    private static Logger logger = LoggerFactory.getLogger(NettyConfiguration.class);
    private static ThreadPoolExecutor pool;

    private static HandlerManager handlerManager;

    @Bean
    public SessionManager nettySessionManager() {
        ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<>();
        return new SessionManager(map);
    }

    @Bean
    public ThreadPoolExecutor businessThreadPoolExecutor() {
        //todo 后续变为可配置的
        ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 4, 6,
                TimeUnit.MINUTES, new ArrayBlockingQueue<>(2000));
        setPool(pool);
        return pool;
    }

    @Bean
    public HandlerManager handlerManager() {
        Map<String, TaskHandler> map = new HashMap<>();
        HandlerManager handlerManager = new HandlerManager(map);
        Map<String, TaskHandler> result = SpringUtil.getApplicationContext().getBeansOfType(TaskHandler.class);
        if (result != null) {
            logger.info("-----------开始装配handlerManager----------");
            result.forEach((k, v) -> {
                logger.info("装配handlerManager," + "name:" + k);
                String version = v.getVersion();
                String actionType = v.getActionType();
                if (StringUtils.isEmpty(version) || StringUtils.isEmpty(actionType)) {
                    logger.error(k + "的version和actionType都不能为空");
                } else {
                    String key = HandlerManager.getKey(version, actionType);
                    map.put(key, v);
                    logger.info("handlerManager装配成功," + "name为" + k + "的taskHandler");
                }
            });
        }
        setHandlerManager(handlerManager);
        return handlerManager;
    }

    public static ThreadPoolExecutor getPool() {
        return pool;
    }

    public static void setPool(ThreadPoolExecutor pool) {
        NettyConfiguration.pool = pool;
    }

    public static HandlerManager getHandlerManager() {
        return handlerManager;
    }

    public static void setHandlerManager(HandlerManager handlerManager) {
        NettyConfiguration.handlerManager = handlerManager;
    }
}
